#Copyright 2009-2010 by Ward, David J ( pymethius@ominian.net )
import weakref
from logging import getLogger
log = getLogger(__name__)

from twisted.internet.task import LoopingCall

from auth import Auth
from webmud.models.users import Users


class AdminAuth(Auth):
    
    def initialize(self):
        self.users = Users()
        self._aggroLoop = self._aggroLoop = LoopingCall(self._aggregator, weakref.proxy(self.sendMessage))
    
    def users(self, id, action, *args):
        """
            Expose the models.User
            TODO - had a thought to stream line the calling process involving decorators and __call__ handler in models... will have to test later
        """
        print "Client request action %s " % action
        if action[0] == "_":
            raise Exception("Unauthorized model action request")
        if not hasattr(self.users, action):
            raise Exception("unsupported")
        
        #If this fail's, let it bubble up    
        action = getattr(self.users, action)
        action(self.sendResponse ,id, *args)
    
    def _aggregator(self, bmSendMessage):
        """
            Support method meant to poll realm.UserRegistry and push all currently registered users
            Primary purpose is a debugging tool
        """
        if bmSendMessage is None:
            #Hopefully this class will be held from GC until this get's to close up shop
            self._aggroLoop.stop()
            del self._aggroLoop
            
        self.realm
            
        
        
    def ureg(self, id, status):
        """
            In the future this will be refactored to incorporate some sort observer pattern or signal system... whatever is cheaper
        """
        log.info("Client User Registry model is %s" % status)
        self._aggregator = None
        if status == "ready":
            # Start aggregator
            self._aggroLoop.start()
        else:
            self._aggroLoop.stop()
        
    
    
        
        